import axios from 'axios'
import $rotuer from '../router/index'
import { Message } from 'element-ui'

//设置请求拦截器
axios.interceptors.request.use((config)=>{
    //携带必要的请求头
    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');
    return config;
},(error)=>{
    return Promise.reject(error);
});

//设置响应拦截器
axios.interceptors.response.use((res)=>{
    return res;
},(error)=>{
    if( error.response.status == 401 ){
        Message({message:'身份认证失败,登陆过期',type:'error'})
        //删除token
        localStorage.removeItem('token');
        //删除userinfo
        localStorage.removeItem('userinfo');
        //跳转登录页
        $rotuer.push('/login');
    }
    else if( error.response.status == 404 ){
        Message({message:'访问路径有误',type:'error'})
        
    }
    else if( error.response.status == 500 ){
        Message({message:'服务器内部错误!',type:'error'})
        
    }

    return Promise.reject(error);
});

//导出axios
export default axios;